package com.base.cn.platform.os.service.user.address;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.user.address.CusUserAddressDao;
import com.base.cn.platform.os.entity.manage.area.SysArea;
import com.base.cn.platform.os.entity.user.address.CusUserAddress;
import com.base.cn.platform.os.service.manage.area.SysAreaService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 收货地址Biz
 * @author ll
 * @date 2018/5/28 11:08
 */
@Service
public class CusUserAddressBiz extends BaseBiz<CusUserAddress,CusUserAddressDao> {

    @Autowired
    private SysAreaService sysAreaService;


    /**
     * 保存收货地址
     *
     * @param userAddress 收货地址属性对象
     * @return Map<String,Object>
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public CusUserAddress saveUserAddress(CusUserAddress userAddress) {
        if (DataUtil.idIsNotNull(userAddress.getId())) {//修改
            CusUserAddress _userAddress = this.findById(userAddress.getId());
            _userAddress.setReceiver(userAddress.getReceiver());
            _userAddress.setProvinceId(userAddress.getProvinceId());
            _userAddress.setCityId(userAddress.getCityId());
            _userAddress.setTownId(userAddress.getTownId());
            _userAddress.setAddress(userAddress.getAddress());
            _userAddress.setPostCode(userAddress.getPostCode());
            _userAddress.setMobile(userAddress.getMobile());
            if (userAddress.getStatus() != null && userAddress.getStatus() == 1) {
                _userAddress.setStatus(userAddress.getStatus());
                List<CusUserAddress> userAddressList = this.queryUserAddressListByUserId(userAddress.getUserId(),false);
                if (ObjectUtils.isNotEmpty(userAddressList)) {
                    for (CusUserAddress u : userAddressList) {
                        u.setStatus(2);
                    }
                    this.updateBatch(userAddressList);
                }
            }
            this.updateById(_userAddress,null);
            return _userAddress;
        } else {//添加
            if (userAddress.getStatus() == null || userAddress.getStatus() == 0) {
                userAddress.setStatus(2);
            } else if (userAddress.getStatus() == 1) {
                List<CusUserAddress> userAddressList = this.queryUserAddressListByUserId(userAddress.getUserId(),false);
                if (ObjectUtils.isNotEmpty(userAddressList)) {
                    for (CusUserAddress u : userAddressList) {
                        u.setStatus(2);
                    }
                    this.updateBatch(userAddressList);
                }
            }
            this.save(userAddress);
            return userAddress;
        }
    }


    /**
     * 修改收货地址默认状态
     *
     * @param id      地址ID
     * @param isFirst 默认状态，1是，2不是
     */
    public void updateUserAddressIsFirst(BigDecimal id, Integer isFirst) {
        CusUserAddress userAddress = this.findById(id);
        if (ObjectUtils.isNotEmpty(userAddress)) {
            userAddress.setStatus(isFirst);
            if (isFirst == 1) {
                List<CusUserAddress> userAddressList = this.queryUserAddressListByUserId(userAddress.getUserId(),false);
                if (ObjectUtils.isNotEmpty(userAddressList)) {
                    for (CusUserAddress u : userAddressList) {
                        u.setStatus(2);
                    }
                    this.updateBatch(userAddressList);
                }
            }else{
                    return;
            }
            this.updateById(userAddress,null);
        }
    }

    /**
     * 获取用户地址列表
     *
     * @param userId
     * @return
     */
    public List<CusUserAddress> queryUserAddressListByUserId(BigDecimal userId,boolean setUserAddress) {
        if (DataUtil.idIsNotNull(userId)){
            return queryUserAddressListByUserIds(userId+"",setUserAddress);

        }
        return null;
    }

    /**
     * 获取用户地址列表
     *
     * @param userIds
     * @return
     */
    public List<CusUserAddress> queryUserAddressListByUserIds(String userIds,boolean setUserAddress) {
        String whereSql = "";
        if (StringUtils.isNotEmpty(userIds)){
            whereSql = " userId in (" + userIds +") order by status asc,createTime desc";
        }
        if (StringUtils.isNotEmpty(whereSql)){
            List<CusUserAddress> userAddresses=this.find(whereSql,null, null);
            userAddresses = setUserAddressListArea(userAddresses,setUserAddress);
            return userAddresses;
        }
        return null;
    }


    /**
     * 查询列表
     *
     * @param page        翻页
     * @param userAddress 用户地址
     * @return
     */
    public PageInfo<CusUserAddress> queryUserAddressListPage(Pagination page, CusUserAddress userAddress,boolean setUserAddress) {
        String where = this.whereSqlUserAddress(userAddress);
        PageInfo<CusUserAddress> pageInfo =this.findPage(where,page,null);
        pageInfo.setList(setUserAddressListArea(pageInfo.getList(),setUserAddress));
        return pageInfo;
    }

    /**
     * 查询列表

     * @param userAddress 用户地址
     * @return
     */
    public List<CusUserAddress> queryUserAddressList(CusUserAddress userAddress,boolean setUserAddress) {
        String where = this.whereSqlUserAddress(userAddress);
        List<CusUserAddress> userAddresses =this.find(where,null,null);
        userAddresses = setUserAddressListArea(userAddresses,setUserAddress);
        return userAddresses;
    }


    /**
     * 查询用户
     * @param addressId 用户地址
     * @return
     */
    public CusUserAddress queryUserAddressById(BigDecimal addressId,boolean setUserAddress) {
        CusUserAddress userAddresses =this.findById(addressId);
        userAddresses = setUserAddressArea(userAddresses,setUserAddress);
        return userAddresses;
    }


    /**
     * 根据Id删除
     * @param addressId
     */
    public void deleteUserAddressById(BigDecimal addressId){
        this.deleteById(addressId);
    }

    /**
     * 条件搜索
     *
     * @param userAddress
     * @return
     */
    public String whereSqlUserAddress(CusUserAddress userAddress) {
        String whereSql = "1=1";
        if (userAddress != null) {
            if (DataUtil.idIsNotNull(userAddress.getUserId())) {
                whereSql += " and userId =" + userAddress.getUserId();
            }
            if (DataUtil.idIsNotNull(userAddress.getCityId())) {
                whereSql += " and cityId =" + userAddress.getCityId();
            }
            if (DataUtil.idIsNotNull(userAddress.getTownId())) {
                whereSql += " and townId =" + userAddress.getTownId();
            }
            if (DataUtil.idIsNotNull(userAddress.getProvinceId())) {
                whereSql += " and provinceId =" + userAddress.getProvinceId();
            }
            if (StringUtils.isNotEmpty(userAddress.getReceiver())) {
                whereSql += " and address='" + userAddress.getReceiver() + "'";
            }
            if (ObjectUtils.isNotEmpty(userAddress.getStatus())) {
                whereSql += " and status = " + userAddress.getStatus();
            }
        }
        whereSql += " order by id desc";
        return whereSql;
    }

    /**
     * 设置地址路径的地区对象
     *
     * @param userAddress 地址对象
     */
    public CusUserAddress setUserAddressArea(CusUserAddress userAddress,boolean setUserAddress) {
        if (ObjectUtils.isNotEmpty(userAddress)) {
            List<CusUserAddress> userAddressList = new ArrayList<>();
            userAddressList.add(userAddress);
            this.setUserAddressListArea(userAddressList,setUserAddress);
            return userAddressList.get(0);
        }
        return userAddress;
    }

    /**
     * 设置地址路径的地区对象
     *
     * @param userAddressList 地址列表
     */
    public List<CusUserAddress> setUserAddressListArea(List<CusUserAddress> userAddressList,boolean setUserAddress) {
        if (ObjectUtils.isNotEmpty(userAddressList)&&setUserAddress) {
            String provinceIds = userAddressList.stream().map(e -> e.getProvinceId().toString()).collect(Collectors.joining(","));
            String ciytIds = userAddressList.stream().map(e -> e.getCityId().toString()).collect(Collectors.joining(","));
            String townIds = userAddressList.stream().map(e -> e.getTownId().toString()).collect(Collectors.joining(","));
            Map<BigDecimal, SysArea> userAreaMap = sysAreaService.querySysAreaMapByIds(provinceIds + "," + ciytIds + "," + townIds);
            if (ObjectUtils.isNotEmpty(userAreaMap)) {
                for (CusUserAddress ua : userAddressList) {
                    ua.setProvince(userAreaMap.get(ua.getProvinceId()));
                    ua.setCity(userAreaMap.get(ua.getCityId()));
                    ua.setTown(userAreaMap.get(ua.getTownId()));
                }
            }
        }
        return userAddressList;
    }
}
